<?php

/**
 * Description:
 * User: Vijay <1937832819@qq.com>
 * Date: 2020/08/27
 * Time: 14:35
 */

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\VarietieRequest;
use App\Http\Traits\TraitResource;
use App\Jobs\VarietiesXlsxJob;
use App\Jobs\XlsxJob;
use App\Models\ClosingData;
use Illuminate\Http\Request;
use App\Models\Exchange;
use Illuminate\Support\Facades\View;

class ClosingDataController extends Controller
{
    use TraitResource;

    public function __construct()
    {
        $today_start    = strtotime(date('Y-m-d', time()));
        // 默认查询昨天的
        $start_time = date('Y-m-d', $today_start - 86400);
        $end_time   = date('Y-m-d', $today_start);
        $timeRes = [
            'start_time' => $start_time,
            'end_time' => $end_time,
        ];
        self::$model       = ClosingData::class;
        self::$controlName = 'closing_data';
        View::share($timeRes);
    }

    /**
     * Description:
     * User: Vijay <1937832819@qq.com>
     * Date: 2020/9/2
     * Time: 20:46
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Contracts\View\Factory|\Illuminate\Http\Response|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        if ($request->isMethod('post')) {
            $keyword       = $request->input('keyword', '');
            $delete        = $request->input('delete', 0);
            $times         = $request->input('times', '');
            $exchange_code = $request->input('exchange_code', '');
            $page          = $request->input('page', 1);
            $limit         = $request->input('limit', 10);
            $query         = self::$model::query();
            $today         = time();
            $today_start   = strtotime(date('Y-m-d', $today));
            switch ($delete) {
                case '1':
                    $query->onlyTrashed();
                    break;
                case '2':
                    $query->withTrashed();
                    break;
                default:
                    break;
            }
            if ($exchange_code != '') {
                $query->where('exchange_code', '=', $exchange_code);
            }
            if ($keyword != '') {
                $query->where(function ($q) use ($keyword) {
                    $q->where('varietie_name', '=', '%' . $keyword . '%')
                        ->orWhere('varietie_code', '=', $keyword);
                });
            }
            if ($times != '') {
                $timeArr    = explode('~', $times);
                $start_time = trim($timeArr[0]);
                $end_time   = trim($timeArr[1]);
            } else {
                // 默认查询昨天的
                $start_time = date('Y-m-d', $today_start - 86400 * 15);
                $end_time   = date('Y-m-d', $today_start);
            }
            $timeRes = getTimeFormat('', $start_time, $end_time);
            $query->where('deal_time_stamp', '>=', $timeRes['start_time_str'])->where('deal_time_stamp', '<=', $timeRes['end_time_str']);
            $list = $query->orderBy('id', 'desc')
                ->get();
            $res  = self::getPageData($list, $page, $limit);
            return $this->resJson(0, '获取成功', $res['data'], ['count' => $res['count']]);
        }
        $exchange_list = Exchange::all();
        return view('admin.' . self::$controlName . '.index', [
            'control_name'  => self::$controlName,
            'delete_list'   => self::$model::$delete,
            'exchange_list' => $exchange_list,
        ]);
    }

    /**
     * Description:
     * User: Vijay <1937832819@qq.com>
     * Date: 2020/9/2
     * Time: 21:37
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create()
    {
        $exchange_list = Exchange::all();
        return view(
            'admin.' . self::$controlName . '.create',
            [
                'control_name'  => self::$controlName,
                'exchange_list' => $exchange_list,
            ]
        );
    }

    /**
     * Description:
     * User: Vijay <1937832819@qq.com>
     * Date: 2020/9/2
     * Time: 22:09
     * @param VarietieRequest $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function store(VarietieRequest $request)
    {
        $model = new self::$model;
        try {
            $model::create($request->input());
            return $this->resJson(0, '操作成功');
        } catch (\Exception $e) {
            return $this->resJson(1, $e->getMessage());
        }
    }

    /**
     * Description:
     * User: Vijay <1937832819@qq.com>
     * Date: 2020/9/2
     * Time: 22:25
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit($id)
    {
        $exchange_list = Exchange::all();
        $info          = self::$model::find($id);
        return view('admin.' . self::$controlName . '.edit', [
            'info'          => $info,
            'control_name'  => self::$controlName,
            'exchange_list' => $exchange_list,
        ]);
    }

    /**
     * Description:
     * User: Vijay <1937832819@qq.com>
     * Date: 2020/9/2
     * Time: 22:26
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function open(Request $request)
    {
        $info = self::$model::find($request->id);
        if (empty($info)) {
            return $this->resJson(1, '没有该条记录');
        }
        try {
            $res = $info->update($request->input());
            return $this->resJson(0, '操作成功', $res);
        } catch (\Exception $e) {
            return $this->resJson(1, $e->getMessage());
        }
    }

    /**
     * Description:
     * User: Vijay <1937832819@qq.com>
     * Date: 2020/9/2
     * Time: 22:25
     * @param VarietieRequest $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function update(VarietieRequest $request)
    {
        $info = self::$model::find($request->id);
        if (empty($info)) {
            return $this->resJson(1, '没有该条记录');
        }
        try {
            $res = $info->update($request->input());
            return $this->resJson(0, '操作成功', $res);
        } catch (\Exception $e) {
            return $this->resJson(1, $e->getMessage());
        }
    }

    /**
     * Description:
     * User: Vijay <1937832819@qq.com>
     * Date: 2020/09/09
     * Time: 11:21
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     */
    public function import(Request $request)
    {
        $caType = $request->input('ca_type', 'closing_datas');
        if (!$request->isMethod('post')) {
            return $this->resJson(1, '请求方式错误');
        }
        //上传文件
        if (!$request->hasFile('file')) {
            return $this->resJson(1, '请上传文件');
        }
        //设置文件后缀白名单
        $allowExt = ["csv", "xls", "xlsx"];
        //设置存储目录
        $date    = date('Ymd');
        $tmpPath = '/uploads/' . $date;
        // 绝对路径
        $dirPath = public_path($tmpPath);
        //如果目标目录不能创建
        if (!is_dir($dirPath) && !mkdir($dirPath, 0777, true)) {
            return $this->resJson(1, '上传目录没有创建文件夹权限');
        }
        //如果目标目录没有写入权限
        if (is_dir($dirPath) && !is_writable($dirPath)) {
            return $this->resJson(1, '上传目录没有写入权限');
        }
        //获取文件
        $file = $request->file('file');
        //校验文件
        if (!isset($file) || !$file->isValid()) {
            return $this->resJson(1, '上传失败');
        }
        $ext = $file->getClientOriginalExtension(); //上传文件的后缀
        //判断是否是Excel
        if (empty($ext) or in_array(strtolower($ext), $allowExt) === false) {
            return $this->resJson(1, '不允许的文件类型');
        }
        //生成文件名
        $fileName = uniqid() . '_' . dechex(microtime(true)) . '.' . $ext;
        try {
            //存储文件
            $file->move($dirPath, $fileName);
            // 获取文件路径
            $filename = $dirPath . '/' . $fileName;
            if (!is_file($filename)) {
                return $this->resJson(1, '未找到该文件');
            }
            // 队列处理表格数据
            if ($caType == 'varieties') {
                VarietiesXlsxJob::dispatch($filename);
            } else if ($caType == 'closing_datas') {
                XlsxJob::dispatch($filename);
            }
            return $this->resJson(0, '上传成功，已在后台处理数据');
        } catch (\Exception $ex) {
            return $this->resJson(1, $ex->getTraceAsString());
        }
    }
}
